﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using FastTravel.BusinessLogic;
using FastTravel.DataAccess.Base;
using FastTravel.DB;
using FastTravel.DB.Enums;
using FastTravel.DB.Helpers;
using FastTravel.Utilites;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace FastTravel.IntranetWeb
{
	public partial class CustomerList : BasePage
	{
		/// <summary>
		/// Загрузка страницы
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty((string)Session["customerID"]))
			{
				ClearDetailFields();
			}

			if (!ExtNet.IsAjaxRequest)
			{
				// Заполняем дроп-даун семейного положения клиента

				Type marritalType = typeof(MarritalStatus);
				Dictionary<int, string> statusList = EnumMetadataConverter.GetListItems(marritalType);

				var dropdawnList = new List<object>();

				foreach (var item in statusList)
				{
					dropdawnList.Add(new { Text = item.Value, Value = item.Key });
				}
				this.storeMarritialStatus.DataSource = dropdawnList;
				this.storeMarritialStatus.DataBind();
			}
		}

		/// <summary>
		/// Обработчик кнопки поиска клиентов
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnSearchCustomerClick(object sender, DirectEventArgs e)
		{
			grdCustomer.Reload();
			toolbarBottomPaging.SetPageIndex(0);
		}

		/// <summary>
		/// Получение списка клиентов
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e">Параметры запроса</param>
		protected void StoreRefresh(object sender, StoreRefreshDataEventArgs e)
		{
			int totalCount = 0;
			
			string filterByFirstName = txtFilterFirstName.Text == "" ? string.Empty : txtFilterFirstName.Text;
			string filterByLastName = txtFilterLastName.Text == "" ? string.Empty : txtFilterLastName.Text;
			string filterByMiddleName = txtFilterMiddleName.Text == "" ? string.Empty : txtFilterMiddleName.Text;

			var customerList = CustomerManager.GetPage(e.Start, e.Limit, e.Sort, e.Dir.ToString(), false, filterByFirstName, 
				filterByLastName, filterByMiddleName, out totalCount);

			e.Total = totalCount;

			this.grdCustomer.GetStore().DataSource = customerList;
		}


		/// <summary>
		/// Отображение детальной информации
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e">Аргумент с параметром</param>
		protected void RowSelected(object sender, DirectEventArgs e)
		{
			string customerId = e.ExtraParams["ID"];
			

			if (!string.IsNullOrEmpty(customerId))
			{
				var currentDetailCustomer = CustomerManager.Get(int.Parse(customerId));

				if (currentDetailCustomer != null)
				{
					Passport passport = CustomerManager.GetPassport(currentDetailCustomer.ID);

					// Персональная информация

					txtDetailFirstName.Text = currentDetailCustomer.FirstName;
					txtDetailFirstName.Disabled = false;

					txtDetailLastName.Text = currentDetailCustomer.LastName;
					txtDetailLastName.Disabled = false;

					txtDetailMiddleName.Text = currentDetailCustomer.MiddleName;
					txtDetailMiddleName.Disabled = false;

					if (currentDetailCustomer.BirthDate.CompareWithoutSeconds(timeForMSSQLServer) != 0)
					{
						dateDetailBirth.SelectedDate = currentDetailCustomer.BirthDate;
					}
					dateDetailBirth.Disabled = false;

					// Контактная информация

					txtDetailAddress1.Text = currentDetailCustomer.AddressLine1;
					txtDetailAddress1.Disabled = false;

					txtDetailAddress2.Text = currentDetailCustomer.AddressLine2;
					txtDetailAddress2.Disabled = false;

					txtDetailEmail.Text = currentDetailCustomer.Email;
					txtDetailEmail.Disabled = false;

					txtDetailPhoneHom.Text = currentDetailCustomer.PhoneHome == 0 
												? "" 
												: currentDetailCustomer.PhoneHome.ToString();
					txtDetailPhoneHom.Disabled = false;

					txtDetailPhoneMob.Text = currentDetailCustomer.PhoneMobile == 0
					                         	? ""
					                         	: currentDetailCustomer.PhoneMobile.ToString();
					txtDetailPhoneMob.Disabled = false;

					txtDetailPhoneWrk.Text = currentDetailCustomer.PhoneWork == 0
					                         	? ""
					                         	: currentDetailCustomer.PhoneWork.ToString();
					txtDetailPhoneWrk.Disabled = false;

					// Паспортные данные)

					if (passport != null)
					{
						txtDetailPassportNumber.Text = passport.Number;
						txtDetailAuthority.Text = passport.Authority;
						
						dateFieldTo.Text = passport.IssueDate.CompareWithoutSeconds(timeForMSSQLServer) != 0
						                     	? passport.IssueDate.Date.ToString()
						                     	: "";
						
						dateFieldFrom.Text = passport.ExpiryDate.CompareWithoutSeconds(timeForMSSQLServer) != 0
						                   		? passport.ExpiryDate.Date.ToString()
						                   		: "";
					}

					txtDetailPassportNumber.Disabled = false;
					txtDetailAuthority.Disabled = false;
					dateFieldTo.Disabled = false;
					dateFieldFrom.Disabled = false;

					// Дополнительная информация

					txtDetailJobPlace.Text = currentDetailCustomer.JobPlacement;
					txtDetailJobPlace.Disabled = false;

					txtDetailProfession.Text = currentDetailCustomer.Profession;
					txtDetailProfession.Disabled = false;

					int statusIndex = Array.IndexOf(Enum.GetValues(typeof(MarritalStatus)), currentDetailCustomer.MarritalStatus);
					comboMarritialStatus.SelectedIndex = statusIndex;
					comboMarritialStatus.Disabled = false;
					
					
					btnSaveDetail.Disabled = false;
				}
				else
				{
					// Очистка полей с детальной информацией

					ClearDetailFields();
					btnSaveDetail.Disabled = true;
				}
			}
			Session["customerID"] = customerId;
		}

		/// <summary>
		/// Сохранить детальную измененную информацию о клиенте
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnSaveDetailClick(object sender, DirectEventArgs e)
		{
			string id = (string) Session["customerID"];
			if (!string.IsNullOrEmpty(id))
			{
				int currentCustomerId = Convert.ToInt32(id);
			
				// Проверяем поля и создаем клиента
				string lastNameForSave = txtDetailLastName.Text ?? string.Empty;
				string firstNameforSave = txtDetailFirstName.Text ?? string.Empty;
				string middleNameForSave = txtDetailMiddleName.Text ?? string.Empty;
				string address1ForSave = txtDetailAddress1.Text ?? string.Empty;
				string address2ForSave = txtDetailAddress2.Text ?? string.Empty;
				string jobForSave = txtDetailJobPlace.Text ?? string.Empty;
				string professionForSave = txtDetailProfession.Text ?? string.Empty;
				string emailForSave = txtDetailEmail.Text ?? string.Empty;
				string authorityForSave = txtDetailAuthority.Text ?? string.Empty;
				string passportNumberForSave = txtDetailPassportNumber.Text ?? string.Empty;

				MarritalStatus marritalForSave = EnumMetadataConverter.NumToEnum<MarritalStatus>(comboMarritialStatus.SelectedIndex);

				Int64 phoneWorkForSave = 0;
				if (!string.IsNullOrWhiteSpace(txtDetailPhoneWrk.Text))
				{
					phoneWorkForSave = Convert.ToInt64(txtDetailPhoneWrk.Text);
				}

				Int64 phoneHomeForSave = 0;
				if (!string.IsNullOrWhiteSpace(txtDetailPhoneHom.Text))
				{
					phoneHomeForSave = Convert.ToInt64(txtDetailPhoneHom.Text);
				}

				Int64 phoneMobileForSave = 0;
				if (!string.IsNullOrWhiteSpace(txtDetailPhoneMob.Text))
				{
					phoneMobileForSave = Convert.ToInt64(txtDetailPhoneMob.Text);
				}

				// если время не указано, устанавливаем его в MSSQL совместимое
				DateTime dateBirthForSave = dateDetailBirth.SelectedDate;
				if (dateBirthForSave.CompareWithoutSeconds(timeEmptyExtControls) == 0)
				{
					dateBirthForSave = timeForMSSQLServer;
				}

				DateTime dateExpirityForSave = dateFieldFrom.SelectedDate;
				if (dateExpirityForSave.CompareWithoutSeconds(timeEmptyExtControls) == 0)
				{
					dateExpirityForSave = timeForMSSQLServer;
				}

				DateTime dateIssueForSave = dateFieldTo.SelectedDate;
				if (dateIssueForSave.CompareWithoutSeconds(timeEmptyExtControls) == 0)
				{
					dateIssueForSave = timeForMSSQLServer;
				}

				CustomerManager.Update(currentCustomerId, firstNameforSave, lastNameForSave, middleNameForSave,
									   phoneHomeForSave, phoneWorkForSave,
									   phoneMobileForSave, professionForSave, jobForSave, marritalForSave, address1ForSave,
									   address2ForSave, dateBirthForSave, emailForSave);

				CustomerManager.UpdatePassport(currentCustomerId, authorityForSave, dateExpirityForSave, dateIssueForSave, passportNumberForSave);

				if (BusinessLogicManager.TryCommit())
				{
					ExtNet.Msg.Notify("Сообщение", "Информация о клиенте успешно обновлена!").Show();
					grdCustomer.Reload();
				}
				else
				{
					ExtNet.Msg.Notify("Ошибка", "Информация о клиенте не была обновлена!").Show();
				}
			}
		}

		
		
		/// <summary>
		/// Создание отчета
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnReportDetailClick(object sender, DirectEventArgs e)
		{
			string id = (string) Session["customerID"];
			if (!string.IsNullOrEmpty(id))
			{
				var win = new Window
				          	{
				          		ID = "wndReport",
				          		Title = "Отчет о клиенте",
				          		Width = Unit.Pixel(600),
				          		Height = Unit.Pixel(400),
				          		Modal = true,
				          		Collapsible = true,
				          		Maximizable = true,
				          		Hidden = true
				          	};

				win.AutoLoad.Url = reportCustomerDetail + "?id=" + id;
				win.AutoLoad.Mode = LoadMode.IFrame;

				win.Render(this.Form);
				win.Show();
			}
		}

		/// <summary>
		/// Очитстка полей с детальной информацией
		/// </summary>
		private void ClearDetailFields()
		{
			// Персональная информация
			
			txtDetailFirstName.Text = string.Empty;
			txtDetailFirstName.Disabled = true;

			txtDetailLastName.Text = string.Empty;
			txtDetailLastName.Disabled = true;

			txtDetailMiddleName.Text = string.Empty;
			txtDetailMiddleName.Disabled = true;

			dateDetailBirth.Text = string.Empty;
			dateDetailBirth.Disabled = true;

			// Контактная информация

			txtDetailAddress1.Text = string.Empty;
			txtDetailAddress1.Disabled = true;

			txtDetailAddress2.Text = string.Empty;
			txtDetailAddress2.Disabled = true;

			txtDetailEmail.Text = string.Empty;
			txtDetailEmail.Disabled = true;

			txtDetailPhoneHom.Text = "";
			txtDetailPhoneHom.Disabled = true;

			txtDetailPhoneMob.Text = "";
			txtDetailPhoneMob.Disabled = true;

			txtDetailPhoneWrk.Text = "";
			txtDetailPhoneWrk.Disabled = true;

			// Паспортные данные

			txtDetailPassportNumber.Text = string.Empty;
			txtDetailPassportNumber.Disabled = true;

			txtDetailAuthority.Text = string.Empty;
			txtDetailAuthority.Disabled = true;

			dateFieldFrom.Text = string.Empty;
			dateFieldFrom.Disabled = true;

			dateFieldTo.Text = string.Empty;
			dateFieldTo.Disabled = true;

			// Дополнительная информация

			txtDetailJobPlace.Text = string.Empty;
			txtDetailJobPlace.Disabled = true;

			txtDetailProfession.Text = string.Empty;
			txtDetailProfession.Disabled = true;
	
			comboMarritialStatus.SelectedIndex = 0;
			comboMarritialStatus.Disabled = true;
		}


		/// <summary>
		/// Удаление клиента
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void BtnDeleteRecordClick(object sender, DirectEventArgs e)
		{
			string id = (string)Session["customerID"];
			if (!string.IsNullOrEmpty(id))
			{
				CustomerManager.Delete(Convert.ToInt32(id));
				if (BusinessLogicManager.TryCommit())
				{
					ExtNet.Msg.Notify("Сообщение", "Клиент удален!").Show();
					grdCustomer.Reload();
					ClearDetailFields();
				}
				else
				{
					ExtNet.Msg.Notify("Ошибка", "Клиент не был удален!").Show();
				}
			}
		}

	}
}